<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="爬宠类型" prop="type">
        <el-tree-select v-model="queryParams.type" :data="typeOptions"
          :props="{ value: 'id', label: 'name', children: 'children' }" value-key="menuId" placeholder="请选择爬宠类型"
          check-strictly />
      </el-form-item>
      <el-form-item label="星级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择星级" clearable>
          <el-option v-for="dict in pet_grade" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="存活状态" prop="survivalStatus">
        <el-select v-model="queryParams.survivalStatus" placeholder="请选择存活状态" clearable>
          <el-option v-for="dict in pet_survival_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="出售状态" prop="sellingStatus">
        <el-select v-model="queryParams.sellingStatus" placeholder="请选择出售状态" clearable>
          <el-option v-for="dict in pet_selling_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="唯一编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入唯一编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="主人号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入主人号码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="出生日期" prop="birthday">
        <el-date-picker clearable v-model="queryParams.birthday" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="创建时间" style="width: 308px;">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['manage:pet:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:pet:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:pet:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:pet:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="petList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column width="55" label="编号" align="center" prop="id" />
      <el-table-column label="爬宠类型" align="center" prop="petTypeName" />
      <el-table-column label="爬宠昵称" align="center" prop="nickName" :show-overflow-tooltip="true" />
      <el-table-column label="商品图片" align="center" prop="petImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.petImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="星级" align="center" prop="grade">
        <template #default="scope">
          <dict-tag :options="pet_grade" :value="scope.row.grade"/>
        </template>
      </el-table-column> -->
      <el-table-column label="星级" align="center" prop="grade">
        <template #default="scope">
          <el-rate v-model="scope.row.grade" disabled :show-score="false" />
        </template>
      </el-table-column>
      <el-table-column label="存活状态" align="center" prop="survivalStatus">
        <template #default="scope">
          <dict-tag :options="pet_survival_status" :value="scope.row.survivalStatus" />
        </template>
      </el-table-column>
      <el-table-column label="出售状态" align="center" prop="sellingStatus">
        <template #default="scope">
          <dict-tag :options="pet_selling_status" :value="scope.row.sellingStatus" />
        </template>
      </el-table-column>
      <el-table-column label="唯一编码" align="center" prop="code" :show-overflow-tooltip="true" />
      <el-table-column label="主人号码" align="center" prop="phone" :show-overflow-tooltip="true" />
      <el-table-column label="出生日期" align="center" prop="birthday" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:pet:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:pet:remove']">删除</el-button>
          <el-button link type="primary" @click="handleAddPhysical(scope.row)"
            v-hasPermi="['manage:physical:add']">添加体征记录</el-button>
            <el-button link type="primary" @click="handleAddInjury(scope.row)"
            v-hasPermi="['manage:injury:add']">添加伤病记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改爬宠对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="petRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="爬宠类型" prop="type">
          <el-tree-select v-model="form.type" :data="typeOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }" value-key="menuId" placeholder="请选择爬宠类型"
            check-strictly />
        </el-form-item>
        <!-- <el-form-item label="星级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择星级">
            <el-option v-for="dict in pet_grade" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="星级" prop="grade">
          <el-rate v-model="form.grade" :show-score="false" @change="$emit('validate')" />
        </el-form-item>
        <el-form-item label="存活状态" prop="survivalStatus">
          <el-select v-model="form.survivalStatus" placeholder="请选择存活状态">
            <el-option v-for="dict in pet_survival_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出售状态" prop="sellingStatus">
          <el-select v-model="form.sellingStatus" placeholder="请选择出售状态">
            <el-option v-for="dict in pet_selling_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker clearable v-model="form.birthday" type="date" value-format="YYYY-MM-DD" placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="爬宠图片" prop="petImage">
          <image-upload v-model="form.petImage" />
        </el-form-item>
        <el-form-item label="爬宠昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入爬宠昵称" />
        </el-form-item>
        <el-form-item label="主人号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入主人号码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增体征记录 -->
    <el-dialog title="新增体征记录" v-model="openPhysical" width="500px" append-to-body>
      <el-form ref="physicalRef" :model="formPhysical" :rules="rulesPhysical" label-width="80px">
        <el-form-item label="爬宠编码" prop="code">
          <el-input v-model="formPhysical.code" placeholder="请输入爬宠编码" disabled />
        </el-form-item>
        <el-form-item label="体长" prop="lengthCm">
          <el-input v-model="formPhysical.lengthCm" placeholder="请输入体长(cm)" />
        </el-form-item>
        <el-form-item label="体重" prop="weightG">
          <el-input v-model="formPhysical.weightG" placeholder="请输入体重(g)" />
        </el-form-item>
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker clearable v-model="formPhysical.recordDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择记录日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formPhysical.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormPhysical">确 定</el-button>
          <el-button @click="cancelPhysical">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增伤病记录 -->
    <el-dialog title="新增伤病记录" v-model="openInjury" width="500px" append-to-body>
      <el-form ref="injuryRef" :model="formInjury" :rules="rulesInjury" label-width="80px">
        <el-form-item label="爬宠编码" prop="code">
          <el-input v-model="formInjury.code" placeholder="请输入爬宠编码" disabled />
        </el-form-item>
        <el-form-item label="伤病类型" prop="injuryCode">
          <el-select v-model="formInjury.injuryCode" placeholder="请选择伤病类型">
            <el-option
              v-for="dict in pet_injury_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker clearable v-model="formInjury.recordDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择记录日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formInjury.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormInjury">确 定</el-button>
          <el-button @click="cancelInjury">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Pet">
import { listPet, getPet, delPet, addPet, updatePet } from "@/api/manage/pet";
import { listType } from "@/api/manage/type";
import { addPhysical } from "@/api/manage/physical";
import { addInjury } from "@/api/manage/injury";

const { proxy } = getCurrentInstance();
const { pet_selling_status, pet_grade, pet_survival_status, pet_injury_type } = proxy.useDict('pet_selling_status', 'pet_grade', 'pet_survival_status', 'pet_injury_type');

const petList = ref([]);
const open = ref(false);
const openPhysical = ref(false);
const openInjury = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const typeOptions = ref([]);// 宠物类型
const dateRange = ref([]);

const data = reactive({
  form: {
    type: null,
  },
  formPhysical: {},
  formInjury: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    grade: null,
    nickName: null,
    survivalStatus: null,
    sellingStatus: null,
    code: null,
    phone: null,
    birthday: null,
  },
  rules: {
    type: [
      { required: true, message: "爬宠类型不能为空", trigger: "change" }
    ],
    grade: [
      { required: true, message: "星级不能为空", trigger: "change" }
    ],
    survivalStatus: [
      { required: true, message: "存活状态不能为空", trigger: "change" }
    ],
    sellingStatus: [
      { required: true, message: "出售状态不能为空", trigger: "change" }
    ],
    birthday: [
      { required: true, message: "出生日期不能为空", trigger: "blur" }
    ],
    petImage: [
      { required: true, message: "选择上传的爬宠图片", trigger: "blur" }
    ],
    phone: [
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号码",
        trigger: "blur"
      }
    ]
  },
  rulesPhysical: {
    lengthCm: [
      { required: true, message: "体长不能为空", trigger: "blur" },
      { pattern: /^\d+(\.\d+)?$/, message: '必须为非负数字，可包含小数', trigger: 'blur' }
    ],
    weightG: [
      { required: true, message: "体重不能为空", trigger: "blur" },
      { pattern: /^\d+(\.\d+)?$/, message: '必须为非负数字，可包含小数', trigger: 'blur' }
    ],
    recordDate: [
      { required: true, message: "记录日期不能为空", trigger: "blur" }
    ],
  },
  rulesInjury: {
    injuryCode: [
      { required: true, message: "伤病编码不能为空", trigger: "change" }
    ],
    recordDate: [
      { required: true, message: "记录日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules, formPhysical, rulesPhysical, formInjury, rulesInjury } = toRefs(data);

/** 查询爬宠列表 */
function getList() {
  loading.value = true;
  listPet(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    petList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
  typeOptions.value = [];
  listType().then(response => {
    typeOptions.value = proxy.handleTree(response.rows, "id");
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 取消按钮
function cancelPhysical() {
  openPhysical.value = false;
  resetPhysical();
}

// 取消按钮
function cancelInjury() {
  openInjury.value = false;
  resetInjury();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    grade: null,
    survivalStatus: null,
    sellingStatus: null,
    code: null,
    phone: null,
    petImage: null,
    birthday: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("petRef");
}

// 体征表单重置
function resetPhysical() {
  formPhysical.value = {
    id: null,
    code: null,
    lengthCm: null,
    weightG: null,
    recordDate: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("physicalRef");
}

// 伤病表单重置
function resetInjury() {
  formPhysical.value = {
    id: null,
    injuryCode: null,
    recordDate: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("injuryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  await getTreeselect();
  open.value = true;
  title.value = "添加爬宠";
}

/** 新增体征记录操作 */
function handleAddPhysical(row){
  resetPhysical();
  formPhysical.value.code = row.code;
  openPhysical.value = true;
}

/** 新增伤病记录操作 */
function handleAddInjury(row){
  resetInjury();
  formInjury.value.code = row.code;
  openInjury.value = true;
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  const _id = row.id || ids.value
  getPet(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改爬宠";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["petRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePet(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPet(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交体征记录按钮 */
function submitFormPhysical() {
  proxy.$refs["physicalRef"].validate(valid => {
    if (valid) {
      addPhysical(formPhysical.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        openPhysical.value = false;
        proxy.$router.push('/record/physical');
        // getList();
      });
    }
  });
}

/** 提交伤病记录按钮 */
function submitFormInjury() {
  proxy.$refs["injuryRef"].validate(valid => {
    if (valid) {
      addInjury(formInjury.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        openInjury.value = false;
        proxy.$router.push('/record/injury');
        // getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除爬宠编号为"' + _ids + '"的数据项？').then(function () {
    return delPet(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/pet/export', {
    ...queryParams.value
  }, `pet_${new Date().getTime()}.xlsx`)
}

getList();
getTreeselect();
</script>
